﻿using AutoMapper;
using B.S.DataBase.SuY.Wirt.Api.AutoList.Command;
using B.S.DataBase.SuY.Wirt.Api.Dto;
using B.S.DataBase.SuYuan.Domain.Model;
using B.S.DataBase.SuYuan.ErrorCode;
using B.S.DataBase.SuYuan.Infrastructrue.Interface;
using MediatR;
using System.Linq;

namespace B.S.DataBase.SuY.Wirt.Api.AutoList.CommandHarder
{
    public class showGoodCommandHarder : IRequestHandler<showGoodCommand, ApiReslit<ApiPaging<GoodDto>>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRepository<Goods> repository;
        private readonly IBaseRepository<Commodity> baseRepository;

        public showGoodCommandHarder(IMapper mapper, IBaseRepository<Goods> repository, IBaseRepository<Commodity> baseRepository)
        {
            this.mapper = mapper;
            this.repository = repository;
            this.baseRepository = baseRepository;
        }

        public Task<ApiReslit<ApiPaging<GoodDto>>> Handle(showGoodCommand request, CancellationToken cancellationToken)
        {
            ApiReslit < ApiPaging < GoodDto >> reslit = new ApiReslit<ApiPaging<GoodDto>>();

            var list = from a in repository.GetAll().Result
                       join b in baseRepository.GetAll().Result on a.CommId equals b.CommId
                       select new GoodDto
                       {
                           G_Id = a.G_Id,
                           CommId = b.CommId,
                           CommName = b.CommName,
                           G_batch = a.G_batch,


                           G_Shelf = a.G_Shelf,

                           G_License = a.G_License,

                           G_enterprise = a.G_enterprise,
                           Refine=a.Refine,
                           G_image = a.G_image,

                       };

            var count = list.Count();
            var page = (int)Math.Ceiling(count * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.G_Id).Skip((request.PageIndex-1)* request.PageSize).Take(request.PageSize);
            ApiPaging<GoodDto>  apiPaging = new ApiPaging<GoodDto>();
            apiPaging.TotalPage = page;
            apiPaging.TotalCount = count;
            apiPaging.List= list.ToList();
            reslit.Code = ApiEnum.查询成功;
            reslit.Msg = ApiEnum.查询成功.ToString();
            reslit.data = apiPaging;
            return Task.FromResult(reslit);

        }
    }
}
